// word-display.js - 单词显示组件逻辑
Component({
  properties: {
    // 可以接收来自父组件的配置
    showExamples: {
      type: Boolean,
      value: true
    },
    showPhonetic: {
      type: Boolean,
      value: true
    },
    // 从父组件接收当前单词数据
    currentWord: {
      type: Object,
      value: {
        word: '',
        pronunciation: null,
        chinese: '',
        examples: [],
        isLearned: false
      },
      observer: function(newVal) {
        // 当当前单词变化时，处理相关考题的高亮显示
        if (newVal && newVal.individual && newVal.individual.pastExamSents) {
          const highlightedSents = this.highlightExamSents(newVal.individual.pastExamSents);
          this.setData({
            highlightedExamSents: highlightedSents
          });
        } else {
          this.setData({
            highlightedExamSents: null
          });
        }
      }
    },
    // 与learning-controls组件保持一致的属性
    isPlaying: {
      type: Boolean,
      value: false
    },
    pronunciationType: {
      type: String,
      value: 'american'
    }
  },

  data: {
    examplesExpanded: false, // 控制例子是否展开，默认不展开
    phrasesExpanded: false, // 控制词组是否展开，默认不展开
    synonymsExpanded: false, // 控制近义词是否展开，默认不展开
    antonymsExpanded: false, // 控制反义词是否展开，默认不展开
    // individual字段展开/折叠状态
    translationsExpanded: false, // 翻译
    idiomExpanded: false, // 习惯用法
    examInfoExpanded: false, // 考试信息
    examSentsExpanded: false, // 相关考题
    mnemonicExpanded: false, // 记忆法
    derivativeExpanded: false, // 派生词汇
    discriminateExpanded: false, // 单词辨别
    highExpressionExpanded: false, // 高级表达
    highlightedExamSents: null, // 高亮显示的相关考题
    // 英文释义相关状态
    englishDefinitions: [], // 英文释义数据
    englishDefinitionsExpanded: false, // 英文释义是否展开
    isLoading: false, // 加载状态
    // 词源相关状态
    wordEtymology: [], // 词源数据
    etymologyExpanded: false // 词源是否展开
  },

  methods: {
    // 高亮显示句子中的当前单词
    highlightCurrentWord: function(sentence) {
      if (!sentence || !this.properties.currentWord.english) {
        return sentence;
      }
      const word = this.properties.currentWord.english;
      const regex = new RegExp('\\b' + word + '\\b', 'gi');
      return sentence.replace(regex, '<span style="background-color:#ffff00">$&</span>');
    },
    
    // 处理相关考题列表，为每个考题添加高亮显示的版本
    highlightExamSents: function(examSents) {
      if (!examSents || !Array.isArray(examSents)) {
        return examSents;
      }
      
      return examSents.map(sent => {
        // 创建一个新对象，避免修改原始数据
        const newSent = Object.assign({}, sent);
        // 添加高亮显示的英文句子
        newSent.highlightedEn = this.highlightCurrentWord(sent.en);
        return newSent;
      });
    },
    
    // 通用切换方法，替代所有单独的toggle方法
    toggleSection: function(e) {
      const sectionKey = e.currentTarget.dataset.section;
      const expandedKey = sectionKey + 'Expanded';
      const newState = {};
      const currentState = !this.data[expandedKey];
      newState[expandedKey] = currentState;
      
      // 如果是英文释义区域并且要展开，则触发网络请求
      if (sectionKey === 'englishDefinitions' && currentState) {
        newState.isLoading = true;
        this.setData(newState);
        this.fetchEnglishDefinitions();
      } 
      // 如果是词源区域并且要展开，则触发网络请求
      else if (sectionKey === 'etymology' && currentState) {
        newState.isLoading = true;
        this.setData(newState);
        this.fetchWordEtymology();
      } else {
        this.setData(newState);
      }
    },
    
    // 获取英文释义的网络请求
    fetchEnglishDefinitions: function() {
      const word = this.properties.currentWord.english;
      if (!word) {
        this.setData({ isLoading: false });
        return;
      }
      
      // 使用真实的网络请求获取英文释义
      // 使用Free Dictionary API (免费开源词典API)
      const apiUrl = `https://api.dictionaryapi.dev/api/v2/entries/en/${encodeURIComponent(word)}`;
      
      wx.request({
        url: apiUrl,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.length > 0) {
            // 处理API响应数据，提取英文释义
            const definitions = [];
            const wordData = res.data[0];
            
            // 遍历所有词性和释义
            if (wordData.meanings && wordData.meanings.length > 0) {
              wordData.meanings.forEach(meaning => {
                const partOfSpeech = meaning.partOfSpeech ? meaning.partOfSpeech + '.' : '';
                
                if (meaning.definitions && meaning.definitions.length > 0) {
                  meaning.definitions.forEach(def => {
                    definitions.push({
                      pos: partOfSpeech,
                      definition: def.definition || '',
                      example: def.example || ''
                    });
                  });
                }
              });
            }
            
            this.setData({
              englishDefinitions: definitions,
              isLoading: false
            });
          } else {
            // 未找到释义或API返回错误
            this.setData({
              englishDefinitions: [{ pos: '', definition: 'No English definition found.', example: '' }],
              isLoading: false
            });
          }
        },
        fail: (error) => {
          console.error('Failed to fetch English definitions:', error);
          this.setData({
            englishDefinitions: [{ pos: '', definition: 'Failed to load definitions. Please try again later.', example: '' }],
            isLoading: false
          });
        },
        complete: () => {
          // 无论成功失败都确保加载状态为false
          if (this.data.isLoading) {
            this.setData({ isLoading: false });
          }
        }
      });
    },
        // 获取单词词源的网络请求和解析
    fetchWordEtymology: function() {
      const word = this.properties.currentWord.english;
      if (!word) {
        this.setData({ isLoading: false });
        return;
      }
      
      // 使用etymologyService获取词源信息
      const etymologyService = require('./etymologyService');
      
      etymologyService.getSimpleEtymology(word)
        .then(result => {
          console.log('Etymology service result:', result);
          
          if (result.success) {
            // 保持词源数据的分块结构，不进行扁平化
            const etymologySections = result.etymologySections || [];
            
            // 词源数据用于显示，保持原始的分块结构
            this.setData({
              wordEtymology: etymologySections,
              isLoading: false
            });
          } else {
            console.warn('Etymology service returned false success:', result.error);
            this.setData({
              wordEtymology: [],
              isLoading: false
            });
          }
        })
        .catch(error => {
          console.error('Failed to fetch word etymology:', error);
          this.setData({
            wordEtymology: [{ pos: '', content: 'Failed to load etymology. Please try again later.' }],
            isLoading: false
          });
        });
    },
    
    // 切换例子的展开/折叠状态
    toggleExamples: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'examples'}}});
    },
    
    // 切换词组的展开/折叠状态
    togglePhrases: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'phrases'}}});
    },
    
    // 切换近义词的展开/折叠状态
    toggleSynonyms: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'synonyms'}}});
    },
    
    // 切换反义词的展开/折叠状态
    toggleAntonyms: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'antonyms'}}});
    },
    
    // 播放单词发音 - 参考learning-controls组件，只触发事件，实际播放由父组件处理
    playPronunciation: function() {
      const { isPlaying } = this.properties;
      
      // 如果正在播放，触发停止事件
      if (isPlaying) {
        this.triggerEvent('stopplay');
      } else {
        // 触发开始播放事件
        this.triggerEvent('playstart');
      }
    },
    
    // 切换翻译的展开/折叠状态
    toggleTranslations: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'translations'}}});
    },
    
    // 切换习惯用法的展开/折叠状态
    toggleIdiom: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'idiom'}}});
    },
    
    // 切换考试信息的展开/折叠状态
    toggleExamInfo: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'examInfo'}}});
    },
    
    // 切换相关考题的展开/折叠状态
    toggleExamSents: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'examSents'}}});
    },
    
    // 切换记忆法的展开/折叠状态
    toggleMnemonic: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'mnemonic'}}});
    },
    
    // 切换派生词汇的展开/折叠状态
    toggleDerivative: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'derivative'}}});
    },
    
    // 切换单词辨别的展开/折叠状态
    toggleDiscriminate: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'discriminate'}}});
    },
    
    // 切换高级表达的展开/折叠状态
    toggleHighExpression: function() {
      this.toggleSection({currentTarget: {dataset: {section: 'highExpression'}}});
    }
  }
});